package com.example.jobback.exception;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.example.jobback.result.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description:全局异常处理器
 * @Author: lhb
 * @Date: 2025/5/23
 */
@RestControllerAdvice
@Hidden
public class GlobalExceptionHandler {


    /**
     * @Description: 处理大部分的运行异常,包括数据库
     * @param ex
     * @return ResponseEntity<Result<Object>>
     * @Author lhb
     * @CreateTime 2025/5/29 22:04
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Result<Object>> handleRuntimeException(RuntimeException ex) {
        ex.printStackTrace();
        System.out.println("运行异常："+ex.getMessage());
        // 将异常信息封装成统一的响应格式
        Result<Object> result = Result.error(ex.getMessage());
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * @Description: 处理 IllegalArgumentException，返回 400 或 422 状态码
     * @param ex
     * @return ResponseEntity<Result<Object>>
     * @Author lhb
     * @CreateTime 2025/5/30
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ResponseEntity<Result<Object>> handleIllegalArgumentException(IllegalArgumentException ex) {
        ex.printStackTrace();
        System.out.println("参数异常："+ex.getMessage());
        String message = ex.getMessage();
        int statusCode;

        if (message.startsWith("CLIENT_ERROR:")) {
            statusCode = HttpStatus.BAD_REQUEST.value();
            message = message.substring("CLIENT_ERROR:".length()).trim();
        } else if (message.startsWith("VALIDATION_ERROR:")) {
            statusCode = HttpStatus.UNPROCESSABLE_ENTITY.value();
            message = message.substring("VALIDATION_ERROR:".length()).trim();
        } else {
            // 默认作为 400 处理
            statusCode = HttpStatus.BAD_REQUEST.value();
        }

        //throw new IllegalArgumentException("VALIDATION_ERROR：无权限");
        //throw new IllegalArgumentException("CLIENT_ERROR：不能新增boss的员工");
        Result<Object> result = new Result<>(statusCode, message);
        return new ResponseEntity<>(result, HttpStatus.valueOf(statusCode));
    }


    /**
     * @Description: 空指针异常，指查找不到资源
     * @param ex
     * @return ResponseEntity<Result<Object>>
     * @Author lhb
     * @CreateTime 2025/6/18 14:36
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseEntity<Result<Object>> handleNullPointerException(NullPointerException ex) {
        ex.printStackTrace();
        System.out.println("空异常："+ex.getMessage());
        Result<Object> result = Result.error(ex.getMessage());
        return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
    }



    /**
     * @Description: AsserTrue注解抛出的异常
     * @param ex
     * @return ResponseEntity<String>
     * @Author lhb
     * @CreateTime 2025/8/6 11:09
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<Result<Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        // 获取所有字段错误
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        // 提取第一个错误的default message（也可以拼接所有错误信息）
        String errorMessage = allErrors.get(0).getDefaultMessage();
        Result<Object> result = Result.error(errorMessage);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }


}
